package com.itheima.Service;

import com.itheima.Entity.SchoolClass;
import com.itheima.Entity.Student;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Scanner;

import static com.itheima.Service.service.LoginUtil.Main.showMainMenu;

public class service {
    public static class LoginUtil {
        // 定义常量
        private static final String CORRECT_USERNAME = "admin";
        private static String CORRECT_PASSWORD = "1234";
        private static final int MAX_ATTEMPTS = 3;
        private static List<SchoolClass> classList = new ArrayList<>();
        private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
        private static List<Student> students = new ArrayList<>();
        private static List<String> classes = new ArrayList<>();

        /**
         * 登录验证方法
         *
         * @return 登录成功返回true，失败返回false
         */
        public static boolean login() {
            classList.add(new SchoolClass("高一(1)班", "教学楼A201", "2023-09-01", "2024-06-30", "张老师"));
            classList.add(new SchoolClass("高二(3)班", "教学楼B105", "2023-09-01", "2024-06-30", "李老师"));

            Scanner scanner = new Scanner(System.in);
            int attempts = 0;
            boolean isLoggedIn = false;

            System.out.println("=== 登录系统 ===");

            while (attempts < MAX_ATTEMPTS && !isLoggedIn) {
                System.out.print("用户名: ");
                String username = scanner.nextLine();

                System.out.print("密码: ");
                String password = scanner.nextLine();

                if (validateCredentials(username, password)) {
                    isLoggedIn = true;
                    System.out.println("登录成功！欢迎，" + username + "！");
                    showMainMenu();
                } else {
                    attempts++;
                    handleFailedAttempt(attempts);
                }
            }

            scanner.close();
            return isLoggedIn;
        }

        /**
         * 验证用户名和密码
         *
         * @param username 输入的用户名
         * @param password 输入的密码
         * @return 验证通过返回true，否则返回false
         */
        private static boolean validateCredentials(String username, String password) {
            return username.equals(CORRECT_USERNAME) && password.equals(CORRECT_PASSWORD);
        }

        /**
         * 处理登录失败的情况
         *
         * @param attempts 当前尝试次数
         */
        private static void handleFailedAttempt(int attempts) {
            int remainingAttempts = MAX_ATTEMPTS - attempts;

            if (remainingAttempts > 0) {
                System.out.println("用户名或密码错误！您还有 " + remainingAttempts + " 次尝试机会。");
            } else {
                System.out.println("用户名或密码错误！您已连续3次登录失败。");
            }
        }


        public class Main {
            public static void main(String[] args) {
                showMainMenu();
            }

            static void showMainMenu() {
                Scanner scanner = new Scanner(System.in);
                boolean isRunning = true;

                while (isRunning) {
                    System.out.println("\n=== 主菜单 ===");
                    System.out.println("1. 班级学员管理");
                    System.out.println("2. 修改密码");
                    System.out.println("3. 退出登录");
                    System.out.print("请选择操作(1-3): ");

                    String choice = scanner.nextLine();

                    switch (choice) {
                        case "1": {
                            System.out.println("您已进入班级学员管理功能。");
                            System.out.println("请输入1进入班级管理菜单。");
                            System.out.println("请输入2进入学员管理菜单。");
                            String input = scanner.nextLine();
                            if (input.equals("1")) {
                                classManagement();
                            } else if (input.equals("2")) {
                                studentManagement();
                            } else {
                                System.out.println("无效的选择，请输入1或2。");
                            }
                            break;
                        }
                        case "2":
                            changePassword();
                            break;
                        case "3":
                            System.out.println("您已退出登录，系统即将关闭。");
                            isRunning = false;
                            break;
                        default:
                            System.out.println("无效的选择，请输入1-3之间的数字。");
                    }
                }

                scanner.close();
                System.exit(0);
            }

            private static void studentManagement() {
                Scanner scanner = new Scanner(System.in);
                boolean backToMain = false;

                while (!backToMain) {
                    System.out.println("\n=== 学员管理 ===");
                    System.out.println("1. 新增学员");
                    System.out.println("2. 修改学员");
                    System.out.println("3. 删除学员");
                    System.out.println("4. 查询学员");
                    System.out.println("5. 违纪扣分");
                    System.out.println("6. 返回主菜单");
                    System.out.print("请选择操作(1-6): ");

                    String choice = scanner.nextLine();

                    switch (choice) {
                        case "1":
                            addStudent();
                            break;
                        case "2":
                            updateStudent();
                            break;
                        case "3":
                            deleteStudent();
                            break;
                        case "4":
                            queryStudent();
                            break;
                        case "5":
                            deductPoints();
                            break;
                        case "6":
                            backToMain = true;
                            break;
                        default:
                            System.out.println("无效的选择，请输入1-6之间的数字。");
                    }
                }
            }

            private static void addStudent() {
                if (students.isEmpty()) {
                    System.out.println("请先添加班级。");
                    return;
                }
                Scanner scanner = new Scanner(System.in);
                System.out.print("请输入学员学号: ");
                Integer studentId = scanner.nextInt();
                scanner.nextLine(); // 清除缓冲区

                // 检查学号是否重复
                for (Student student : students) {
                    Scanner scanner1 = new Scanner(System.in);
                    System.out.print("请输入学员学号: ");
                    Integer studentId1 = scanner.nextInt();
                    scanner.nextLine(); // 清除缓冲区

                    // 检查学号是否重复
                    for (Student student1 : students) {
                        if (student.getId().equals(studentId)) {
                            System.out.println("学号重复，请重新输入！");
                            return;
                        }
                    }

                    System.out.print("请输入学员姓名: ");
                    String name = scanner.nextLine();

                    System.out.print("请输入学员性别(1-男，2-女): ");
                    Integer sex = scanner.nextInt();
                    scanner.nextLine(); // 清除缓冲区

                    System.out.print("请输入学员电话号码: ");
                    String phoneNumber = scanner.nextLine();

                    System.out.print("请输入学员学历: ");
                    String degree = scanner.nextLine();

                    // 展示现有班级列表
                    System.out.println("现有班级列表：");
                    for (int i = 0; i < classList.size(); i++) {
                        System.out.println((i + 1) + ". " + classList.get(i).getClassName());
                    }

                    System.out.print("请选择班级编号: ");
                    int classIndex = scanner.nextInt();
                    scanner.nextLine(); // 清除缓冲区

                    if (classIndex > 0 && classIndex <= classList.size()) {
                        SchoolClass selectedClass = classList.get(classIndex - 1);
//                        Student newStudent = new Student(studentId, name, sex, phoneNumber, degree, selectedClass);
//                        students.add(newStudent);
                        System.out.println("学员添加成功！");
                    } else {
                        System.out.println("无效的班级编号！");
                    }
                }
            }

            private static void updateStudent() {
                System.out.println("修改学员功能尚未实现。");
            }

            private static void deleteStudent() {
                System.out.println("删除学员功能尚未实现。");
            }

            private static void queryStudent() {
                System.out.println("查询学员功能尚未实现。");
            }

            private static void deductPoints() {
                System.out.println("违纪扣分功能尚未实现。");
            }


            /**
             * 班级管理功能
             */

            private static void classManagement() {
                Scanner scanner = new Scanner(System.in);
                boolean backToMain = false;

                while (!backToMain) {
                    System.out.println("\n=== 班级管理 ===");
                    System.out.println("1. 新增班级");
                    System.out.println("2. 删除班级");
                    System.out.println("3. 修改班级");
                    System.out.println("4. 查询所有班级");
                    System.out.println("5. 返回主菜单");
                    System.out.print("请选择操作(1-5): ");

                    String choice = scanner.nextLine();

                    switch (choice) {
                        case "1":
                            addClass();
                            break;
                        case "2":
                            deleteClass();
                            break;
                        case "3":
                            modifyClass();
                            break;
                        case "4":
                            queryClassMenu();
                            break;
                        case "5":
                            backToMain = true;
                            break;
                        default:
                            System.out.println("无效的选择，请输入1-5之间的数字。");
                    }
                }
            }

            // 新增班级（根据新实体类调整）
            private static void addClass() {
                Scanner scanner = new Scanner(System.in);
                System.out.print("请输入学员学号: ");
                Integer studentId = scanner.nextInt();
                scanner.nextLine(); // 清除缓冲区

                // 检查学号是否重复
                for (Student student : students) {
                    if (student.getId().equals(studentId)) {
                        System.out.println("学号重复，请重新输入！");
                        return;
                    }
                }

                System.out.print("请输入学员姓名: ");
                String name = scanner.nextLine();

                System.out.print("请输入学员性别(1-男，2-女): ");
                Integer sex = scanner.nextInt();
                scanner.nextLine(); // 清除缓冲区

                System.out.print("请输入学员电话号码: ");
                String phoneNumber = scanner.nextLine();

                System.out.print("请输入学员学历: ");
                String degree = scanner.nextLine();

                // 展示现有班级列表
                System.out.println("现有班级列表：");
                for (int i = 0; i < classList.size(); i++) {
                    System.out.println((i + 1) + ". " + classList.get(i).getClassName());
                }

                System.out.print("请选择班级编号: ");
                int classIndex = scanner.nextInt();
                scanner.nextLine(); // 清除缓冲区

                if (classIndex > 0 && classIndex <= classList.size()) {
                    SchoolClass selectedClass = classList.get(classIndex - 1);
                    Student newStudent = new Student(studentId, name, sex, phoneNumber, degree, selectedClass.getClassName());
                    students.add(newStudent);
                    System.out.println("学员添加成功！");
                } else {
                    System.out.println("无效的班级编号！");
                }
            }

            // 检查班级名称是否存在
            private static boolean isClassNameExists(String className) {
                for (SchoolClass sc : classList) {
                    if (sc.getClassName().equalsIgnoreCase(className.trim())) {
                        return true;
                    }
                }
                return false;
            }

            // 删除班级
            private static void deleteClass() {
                Scanner scanner = new Scanner(System.in);

                System.out.println("\n=== 删除班级 ===");
                showAllClasses();

                if (classList.isEmpty()) {
                    return;
                }

                System.out.print("请输入要删除的班级名称: ");
                String className = scanner.nextLine();
                boolean removed = false;
                for (int i = 0; i < classList.size(); i++) {
                    if (classList.get(i).getClassName().equalsIgnoreCase(className.trim())) {
                        classList.remove(i);
                        removed = true;
                        break;
                    }
                }

                if (removed) {
                    System.out.println("班级删除成功！");
                } else {
                    System.out.println("未找到该班级！");
                }
            }

            // 修改班级（根据新实体类调整）
            private static void modifyClass() {
                Scanner scanner = new Scanner(System.in);

                System.out.println("\n=== 修改班级 ===");
                showAllClasses();

                if (classList.isEmpty()) {
                    return;
                }

                System.out.print("请输入要修改的班级名称: ");
                String className = scanner.nextLine();

                for (SchoolClass sc : classList) {
                    if (sc.getClassName().equalsIgnoreCase(className.trim())) {
                        System.out.println("\n正在修改班级: " + sc.getClassName());

                        // 修改教室位置
                        System.out.print("输入新教室位置(" + sc.getClassroom() + "): ");
                        String newClassroom = scanner.nextLine();
                        if (!newClassroom.isEmpty()) sc.setClassroom(newClassroom);

                        // 修改开课时间
                        System.out.print("输入新开课时间(" + sc.getClassTime() + "): ");
                        String newClassTime = scanner.nextLine();
                        if (!newClassTime.isEmpty()) sc.setClassTime(newClassTime);

                        // 修改结课时间
                        System.out.print("输入新结课时间(" + sc.getClassEndTime() + "): ");
                        String newClassEndTime = scanner.nextLine();
                        if (!newClassEndTime.isEmpty()) sc.setClassEndTime(newClassEndTime);

                        // 修改班主任
                        System.out.print("输入新班主任(" + sc.getHeadTeacher() + "): ");
                        String newHeadTeacher = scanner.nextLine();
                        if (!newHeadTeacher.isEmpty()) sc.setHeadTeacher(newHeadTeacher);

                        System.out.println("班级信息修改成功！");
                        return;
                    }
                }

                System.out.println("未找到该班级！");
            }

//           学员管理菜单
            private static void queryClassMenu() {
                Scanner scanner = new Scanner(System.in);
                boolean backToClassMenu = false;

                while (!backToClassMenu) {
                    System.out.println("\n=== 班级查询 ===");
                    System.out.println("1. 查看所有班级");
                    System.out.println("2. 按班级名称查询");
                    System.out.println("3. 按结课时间查询");
                    System.out.println("4. 返回上一级菜单");
                    System.out.print("请选择查询方式(1-4): ");

                    String choice = scanner.nextLine();

                    switch (choice) {
                        case "1":
                            showAllClasses();
                            break;
                        case "2":
                            queryByClassName();
                            break;
                        case "3":
                            queryByEndDate();
                            break;
                        case "4":
                            backToClassMenu = true;
                            break;
                        default:
                            System.out.println("无效的选择，请输入1-4之间的数字。");
                    }
                }
            }

            // 显示所有班级
            private static void showAllClasses() {
                System.out.println("\n=== 所有班级列表 ===");
                if (classList.isEmpty()) {
                    System.out.println("暂无班级数据");
                    return;
                }

                printClassTable(classList);
            }

            // 按班级名称查询
            private static void queryByClassName() {
                Scanner scanner = new Scanner(System.in);

                System.out.println("\n=== 按班级名称查询 ===");
                System.out.print("请输入班级名称(支持模糊查询): ");
                String keyword = scanner.nextLine().trim().toLowerCase();

                List<SchoolClass> result = new ArrayList<>();
                for (SchoolClass sc : classList) {
                    if (sc.getClassName().toLowerCase().contains(keyword)) {
                        result.add(sc);
                    }
                }

                if (result.isEmpty()) {
                    System.out.println("没有找到匹配的班级");
                } else {
                    System.out.println("找到 " + result.size() + " 个匹配的班级:");
                    printClassTable(result);
                }
            }

            // 按结课时间查询
            private static void queryByEndDate() {
                Scanner scanner = new Scanner(System.in);

                System.out.println("\n=== 按结课时间查询 ===");
                System.out.print("请输入开始日期(格式: YYYY-MM-DD, 直接回车跳过): ");
                String startDateStr = scanner.nextLine().trim();

                System.out.print("请输入结束日期(格式: YYYY-MM-DD, 直接回车跳过): ");
                String endDateStr = scanner.nextLine().trim();

                Date startDate = null;
                Date endDate = null;

                try {
                    if (!startDateStr.isEmpty()) {
                        startDate = DATE_FORMAT.parse(startDateStr);
                    }
                    if (!endDateStr.isEmpty()) {
                        endDate = DATE_FORMAT.parse(endDateStr);
                    }
                } catch (ParseException e) {
                    System.out.println("日期格式错误，请使用YYYY-MM-DD格式");
                    return;
                }

                List<SchoolClass> result = new ArrayList<>();
                for (SchoolClass sc : classList) {
                    try {
                        Date classEndDate = DATE_FORMAT.parse(sc.getClassEndTime());

                        boolean match = true;
                        if (startDate != null && classEndDate.before(startDate)) {
                            match = false;
                        }
                        if (endDate != null && classEndDate.after(endDate)) {
                            match = false;
                        }

                        if (match) {
                            result.add(sc);
                        }
                    } catch (ParseException e) {
                        // 忽略日期格式错误的班级
                    }
                }

                if (result.isEmpty()) {
                    System.out.println("没有找到符合条件的班级");
                } else {
                    System.out.println("找到 " + result.size() + " 个符合条件的班级:");
                    printClassTable(result);
                }
            }

            // 打印班级表格
            private static void printClassTable(List<SchoolClass> classes) {
                System.out.println("----------------------------------------------------------------------------------------");
                System.out.printf("| %-15s | %-15s | %-15s | %-15s | %-15s |%n",
                        "班级名称", "教室位置", "开课时间", "结课时间", "班主任");
                System.out.println("----------------------------------------------------------------------------------------");

                for (SchoolClass sc : classes) {
                    System.out.printf("| %-15s | %-15s | %-15s | %-15s | %-15s |%n",
                            sc.getClassName(),
                            sc.getClassroom(),
                            sc.getClassTime(),
                            sc.getClassEndTime(),
                            sc.getHeadTeacher());
                }
                System.out.println("----------------------------------------------------------------------------------------");
                System.out.println("总计: " + classes.size() + " 个班级");
            }

            /**
             * 修改密码功能
             */
            private static void changePassword() {

                Scanner scanner = new Scanner(System.in);

                System.out.println("\n=== 修改密码 ===");
                System.out.print("请输入当前密码: ");
                String oldPassword = scanner.nextLine();

                if (!oldPassword.equals(CORRECT_PASSWORD)) {
                    System.out.println("当前密码输入错误！");
                    return;
                }
                System.out.print("请输入新密码: ");
                String newPassword = scanner.next();

                System.out.print("请再次输入新密码: ");
                String confirmPassword = scanner.next();

                if (newPassword.equals(confirmPassword)) {
                    CORRECT_PASSWORD = newPassword;
                    System.out.println("密码修改成功！");
                } else {
                    System.out.println("两次输入的新密码不一致，修改失败！");
                }
            }
        }
    }
}


